package cn.wrl.auth.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class JwtService {


    private static final String key = "这个一个加密key";
    private static final String user = "user";
    private static final long token_exp_time = 1000 * 60 * 60 * 24;
    private static final String user_id = "user_id";

    public String token(String userId) {
        Date now = new Date();

        Algorithm algorithm = Algorithm.HMAC256(key);
        String token = JWT.create()
                .withIssuer(user)
                .withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + token_exp_time))
                .withClaim(user_id, userId)
                .sign(algorithm);

        log.info("jwt create success. userId={}", userId);

        return token;
    }

    public boolean verify(String token, String userId) {
        log.info("verifying jwt. user={}", userId);

        try {
            Algorithm algorithm = Algorithm.HMAC256(key);

            JWTVerifier jwtVerifier = JWT.require(algorithm)
                    .withIssuer(user)
                    .withClaim(user_id, userId)
                    .build();

            jwtVerifier.verify(token);
            return true;
        } catch (Exception e) {
            log.error("auth failed. userid={}", userId);
            return false;
        }
    }


}
